package com.taormina.searchservice;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GoogleSearchServiceImpl extends HttpGetSearchService {
	
	private static final String SEARCH_URL = "https://www.google.com/search";
	private static final String QUERY_PREFIX = "?q=";
	private static final Pattern VIDEO_RESULT_PATTERN = Pattern.compile("www\\.youtube\\.com");
	private static final Pattern SEARCH_RESULT_LINK_PATTERN = Pattern.compile("href=\"/url\\?q=([^&]+)");
	
	@Override
	protected String getSearchUrl() {
		return SEARCH_URL;
	}
	
	@Override
	protected String getQueryPrefix() {
		return QUERY_PREFIX;
	}
	
	@Override
	protected List<String> getTopSearchLinks(File xhtmlMarkup) throws IOException {
		
		String markupText = fileToString(xhtmlMarkup);
		
		Matcher linkMatcher = SEARCH_RESULT_LINK_PATTERN.matcher(markupText);
		List<String> links = new ArrayList<String>();
		while (linkMatcher.find()) {
			links.add(linkMatcher.group(1));
		}
		
		List<String> topLinks = new ArrayList<String>();
		
		int linkLimit = links.size() < MAX_RESULTS ? links.size() : MAX_RESULTS;
		
		Matcher videoLinkMatcher;
		for (int i = 0; i < linkLimit; i++) {
			videoLinkMatcher = VIDEO_RESULT_PATTERN.matcher(links.get(i));
			if (!videoLinkMatcher.find()) {
				topLinks.add(links.get(i));
			}
		}
		
		return topLinks;
	}
}
